package com.atguigu.juc;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author tongatong
 * @name SaleTicket
 * @description  多线程买票demo
 *   多线程使用口诀：☆☆☆ 多线程 操作 资源类 ☆☆☆
 *   例子：三个售票员，买50张票
 * @date 2021/8/31
 * @time 19:59
 */
public class SaleTicket {
    public static void main(String[] args) {
        //创建三个售票员，三个线程
        Employee emp1 = new Employee("售票员1");
        Employee emp2 = new Employee("售票员2");
        Employee emp3 = new Employee("售票员3");

        //开启线程，使线程进入就绪状态
        emp1.start();
        emp2.start();
        emp3.start();
    }

}

//资源类
class Ticket {
    private static int count = 50;

    //操作
    //根据高内聚，买票这个操作和 票 相关，所以写到 票 这个类中
    //使用synchronized关键字
    /*public synchronized void sale() {
        while (true) {
            if (count <= 0)
                break;
            System.out.println(Thread.currentThread().getName()+"----余票："+count--+",\t"+"现票："+count);;

        }
    }*/
    //使用juc包
    public void sale() {
        while (true) {
            if (count <= 0)
                break;
            System.out.println(Thread.currentThread().getName()+"----余票："+count--+",\t"+"现票："+count);;

        }
    }

}

class Employee extends Thread {
    public Employee(String name) {
        super(()->{
            Lock lock = new ReentrantLock();
            lock.lock();
            try {
                // access the resource protected by this lock
                new Ticket().sale();
            } finally {
                lock.unlock();
            }
        }, name);
    }
}
